﻿using Cheems.Control.Models.Chat;
using Cheems.Interface.Models.UserManagement;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Cheems.Control.Controls
{
    /// <summary>
    /// 聊天Box
    /// </summary>
    public class ChatBox : UserControl
    {
        public ChatBox()
        {
            HistoryContent = new StackPanel();
            ChatHistoryData = new ObservableCollection<ChatHistory>();
        }


        public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusProperty); }
            set { SetValue(CornerRadiusProperty, value); }
        }
        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ChatBox), new PropertyMetadata(new CornerRadius(5)));

        /// <summary>
        /// 历史聊天区域
        /// </summary>
        public object HistoryContent
        {
            get { return (object)GetValue(HistoryContentProperty); }
            set { SetValue(HistoryContentProperty, value); }
        }
        public static readonly DependencyProperty HistoryContentProperty =
            DependencyProperty.Register("HistoryContent", typeof(object), typeof(ChatBox), new PropertyMetadata(null));


        /// <summary>
        /// 当前聊天区域
        /// </summary>
        public object CurrentContent
        {
            get { return (object)GetValue(CurrentContentProperty); }
            set { SetValue(CurrentContentProperty, value); }
        }
        public static readonly DependencyProperty CurrentContentProperty =
            DependencyProperty.Register("CurrentContent", typeof(object), typeof(ChatBox), new PropertyMetadata(null));

        public ObservableCollection<ChatHistory> ChatHistoryData
        {
            get { return (ObservableCollection<ChatHistory>)GetValue(ChatHistoryDataProperty); }
            set { SetValue(ChatHistoryDataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ChatHistory.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ChatHistoryDataProperty =
            DependencyProperty.Register("ChatHistoryData", typeof(ObservableCollection<ChatHistory>), typeof(ChatBox), new PropertyMetadata(null, OnChatHistoryDataChanged));


        /// <summary>
        /// 当前聊天记录
        /// </summary>
        public ChatHistory CurrentChatData
        {
            get { return (ChatHistory)GetValue(CurrentChatDataProperty); }
            set { SetValue(CurrentChatDataProperty, value); }
        }
        public static readonly DependencyProperty CurrentChatDataProperty =
            DependencyProperty.Register("CurrentChatData", typeof(ChatHistory), typeof(ChatBox), new PropertyMetadata(null, OnCurrentChatDataChanged));

        private static void OnCurrentChatDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ChatBox thisControl = d as ChatBox;
            thisControl.RefreshUI();
        }



        /// <summary>
        /// 上一次历史记录
        /// </summary>
        private List<ChatHistory> _lastChatHistory = new List<ChatHistory>();

        private static void OnChatHistoryDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ChatBox thisControl = d as ChatBox;
            thisControl.RefreshUI();
        }


        private void RefreshUI()
        {
            ChatBox thisControl = this;

            // 先按时间排序
            List<ChatHistory> orderHistoryChat = thisControl.ChatHistoryData.OrderBy(it => it.User.CreatTime).ToList();

            // 移除已经删除的聊天记录
            for (int i = thisControl._lastChatHistory.Count - 1; i >= 0; i--)
            {
                if (!orderHistoryChat.Contains(thisControl._lastChatHistory[i]))
                {
                    thisControl._lastChatHistory.RemoveAt(i);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        // 确保在 UI 线程中执行
                        if (thisControl.HistoryContent is StackPanel stackPanel)
                        {
                            stackPanel.Children.RemoveAt(i);
                        }
                    });
                }
            }

            // 添加缺失的聊天记录
            for (int i = 0; i < orderHistoryChat.Count; i++)
            {
                if (!thisControl._lastChatHistory.Contains(orderHistoryChat[i]))
                {
                    thisControl._lastChatHistory.Insert(i, orderHistoryChat[i]);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        // 确保在 UI 线程中执行
                        if (thisControl.HistoryContent is StackPanel stackPanel)
                        {
                            stackPanel.Children.Insert(i, new SingleChat()
                            {
                                ChatHistory = orderHistoryChat[i],
                            });
                        }
                    });
                }
            }

            // 当前聊天记录
            if (thisControl.CurrentChatData == null)
            {
                thisControl.CurrentContent = null;
            }
            else
            {
                thisControl.CurrentContent = new SingleChat()
                {
                    ChatHistory = thisControl.CurrentChatData,
                };
            }
        }

    }
}
